import React, { useState, useEffect, useMemo } from 'react'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import ImageSliceViewer, {
  ImageSliceGrid,
  clearImageCache,
  type PositionData
} from '@/components/ui/image-slice-viewer'

import { usePieceStore } from '@/store/piece'

export default function ImageSliceDemo() {
  const { storePieces, loadAllPieces, isLoaded, isLoading } = usePieceStore()
  const [selectedGroup, setSelectedGroup] = useState('')
  const [debugMode, setDebugMode] = useState(false)

  // 加载数据
  useEffect(() => {
    loadAllPieces()
  }, [loadAllPieces])

  // 按 URL 前缀分组图片
  const groupedImages = useMemo(() => {
    if (!storePieces.length) return {}

    const groups: Record<
      string,
      {
        imageId: string
        pieces: ((typeof storePieces)[0] & { row: number; col: number })[]
      }
    > = {}

    storePieces.forEach((piece) => {
      if (piece.avatar) {
        // 解析 avatar 格式: "14097_1_2" (imageId_row_col)
        const avatarMatch = piece.avatar.match(/^(\d+)_(\d+)_(\d+)$/)
        if (avatarMatch) {
          const imageId = avatarMatch[1]
          const row = parseInt(avatarMatch[2], 10)
          const col = parseInt(avatarMatch[3], 10)

          if (!groups[imageId]) {
            groups[imageId] = {
              imageId,
              pieces: []
            }
          }
          groups[imageId].pieces.push({ ...piece, row, col })
        }
      }
    })

    return groups
  }, [storePieces])

  const groupKeys = Object.keys(groupedImages)
  const currentGroup = selectedGroup || groupKeys[0]
  const baseUrl = '/api/g/f/p/'

  // 生成所有25个位置的数组 (5x5网格)，并关联对应的碎片数据
  const allPositions = useMemo(() => {
    const positions: PositionData[] = []
    const currentPieces = groupedImages[currentGroup]?.pieces || []

    for (let row = 0; row < 5; row++) {
      for (let col = 0; col < 5; col++) {
        // 查找对应位置的碎片数据
        const piece = currentPieces.find((p) => p.row === row && p.col === col)

        positions.push({
          row,
          col,
          id: `${row}-${col}`,
          name: `(${row},${col})`,
          piece: piece
            ? {
                id: piece.id,
                name: piece.name,
                alias: piece.alias,
                describe: piece.describe,
                score: piece.score,
                avatar: piece.avatar,
                props: piece.props
              }
            : undefined
        })
      }
    }
    return positions
  }, [groupedImages, currentGroup])

  // 处理图片点击
  const handleImageClick = (position: PositionData, index: number) => {
    console.log(`点击了位置 (${position.row}, ${position.col}), 索引: ${index}`)

    if (position.piece) {
      console.log('找到对应碎片:', position.piece)
      console.log('碎片详情:', {
        id: position.piece.id,
        name: position.piece.name,
        alias: position.piece.alias,
        describe: position.piece.describe,
        avatar: position.piece.avatar,
        score: position.piece.score,
        props: position.piece.props,
        position: `(${position.row}, ${position.col})`
      })
    } else {
      console.log(`位置 (${position.row}, ${position.col}) 没有找到对应的碎片`)
    }
  }

  // 清理缓存
  const handleClearCache = () => {
    clearImageCache()
    window.location.reload() // 重新加载页面以重新加载图片
  }

  if (isLoading) {
    return (
      <div className="container mx-auto p-6">
        <div className="text-center">
          <div className="text-lg">正在加载碎片数据...</div>
        </div>
      </div>
    )
  }

  if (!isLoaded || !groupKeys.length) {
    return (
      <div className="container mx-auto p-6">
        <div className="text-center">
          <div className="text-lg">没有找到图片数据</div>
        </div>
      </div>
    )
  }

  return (
    <div className="container mx-auto space-y-6 p-6">
      <div className="space-y-4">
        <h1 className="text-2xl font-bold">图片切片展示（基于碎片数据）</h1>

        {/* 控制面板 */}
        <Card className="p-4">
          <div className="flex flex-wrap items-center gap-4">
            <div className="flex items-center gap-2">
              <label className="text-sm font-medium">图片分组:</label>
              <select
                value={currentGroup}
                onChange={(e) => setSelectedGroup(e.target.value)}
                className="rounded-md border px-3 py-1"
              >
                {groupKeys.map((groupKey) => (
                  <option key={groupKey} value={groupKey}>
                    图片 {groupKey} ({groupedImages[groupKey].pieces.length}{' '}
                    个碎片)
                  </option>
                ))}
              </select>
            </div>
            <Button onClick={handleClearCache} variant="outline" size="sm">
              清理缓存
            </Button>
            <Button
              onClick={() => setDebugMode(!debugMode)}
              variant={debugMode ? 'default' : 'outline'}
              size="sm"
            >
              {debugMode ? '关闭调试' : '开启调试'}
            </Button>
            <Badge variant="secondary">
              当前组: {groupedImages[currentGroup]?.pieces.length || 0} 个碎片
            </Badge>
            <Badge variant="outline">总计: {groupKeys.length} 个图片分组</Badge>
          </div>

          {debugMode && (
            <div className="mt-4 rounded bg-gray-50 p-3">
              <h4 className="mb-2 font-medium">调试信息:</h4>
              <p className="text-sm">当前图片ID: {currentGroup}</p>
              <p className="text-sm">
                完整图片URL: {baseUrl}
                {currentGroup}
              </p>
              <p className="text-sm">
                碎片数量: {groupedImages[currentGroup]?.pieces.length || 0}
              </p>
              <p className="text-sm">
                <a
                  href={`${baseUrl}${currentGroup}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-blue-600 hover:underline"
                >
                  点击测试图片是否能访问
                </a>
              </p>
              <div className="mt-2">
                <p className="text-sm font-medium">碎片信息:</p>
                <div className="max-h-32 overflow-y-auto rounded bg-white p-2 text-xs">
                  {groupedImages[currentGroup]?.pieces
                    .sort((a, b) => a.row * 5 + a.col - (b.row * 5 + b.col))
                    .map((piece) => (
                      <div key={piece.id} className="mb-1">
                        位置({piece.row},{piece.col}): {piece.name}
                        {piece.alias && (
                          <span className="text-blue-600">
                            {' '}
                            [{piece.alias}]
                          </span>
                        )}
                        <br />
                        <span className="text-xs text-gray-600">
                          ID: {piece.id}, 分数: {piece.score}
                          {piece.describe && (
                            <span className="mt-1 block">
                              描述: {piece.describe}
                            </span>
                          )}
                        </span>
                      </div>
                    ))}
                </div>
              </div>
            </div>
          )}
        </Card>

        {/* 图片网格展示 */}
        <Card className="p-6">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold">
                图片切片网格 - 图片 {currentGroup}
              </h2>
              <div className="text-sm text-gray-600">
                {groupedImages[currentGroup]?.pieces.length || 0} / 25
                个位置有碎片数据
              </div>
            </div>

            <ImageSliceGrid
              imageId={currentGroup}
              baseUrl={baseUrl}
              positions={allPositions}
              className="grid-cols-5 gap-3"
              itemClassName="border rounded-lg hover:shadow-md transition-shadow"
              showLabels={true}
              showPieceInfo={true}
              onItemClick={handleImageClick}
            />
          </div>
        </Card>

        {/* 示例：单个图片展示 */}
        <Card className="p-4">
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">单个图片示例</h3>
            <div className="flex items-center gap-4">
              {[
                { row: 0, col: 0, format: 'URL参数格式' },
                { row: 2, col: 2, format: '传统格式' },
                { row: 4, col: 4, format: 'URL参数格式' }
              ].map((example, index) => {
                const position = allPositions.find(
                  (p) => p.row === example.row && p.col === example.col
                )

                return (
                  <div key={index} className="text-center">
                    <div className="group relative">
                      <ImageSliceViewer
                        imageId={currentGroup}
                        row={example.row}
                        col={example.col}
                        baseUrl={baseUrl}
                        width={56}
                        height={56}
                        alt={`示例图片 (${example.row},${example.col})`}
                      />

                      {/* Hover 卡片 */}
                      {position?.piece && (
                        <div className="pointer-events-none absolute bottom-full left-1/2 z-10 mb-2 -translate-x-1/2 opacity-0 transition-opacity duration-200 group-hover:opacity-100">
                          <div className="whitespace-nowrap rounded-lg border border-gray-200 bg-white p-3 text-xs shadow-lg">
                            <div className="mb-1 font-medium text-gray-800">
                              {position.piece.name}
                            </div>
                            {position.piece.alias && (
                              <div className="mb-1 font-mono text-blue-600">
                                [{position.piece.alias}]
                              </div>
                            )}
                            {position.piece.describe && (
                              <div className="mb-1 max-w-48 whitespace-normal text-gray-600">
                                {position.piece.describe}
                              </div>
                            )}
                            <div className="text-gray-500">
                              位置: ({position.row}, {position.col}) | 分数:{' '}
                              {position.piece.score}
                            </div>
                            <div className="absolute left-1/2 top-full -mt-1 -translate-x-1/2">
                              <div className="size-2 rotate-45 border-b border-r border-gray-200 bg-white"></div>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>

                    <div className="mt-1 text-sm text-gray-600">
                      位置 ({example.row},{example.col})
                    </div>
                    <div className="text-xs text-gray-500">
                      {example.format}
                    </div>

                    {/* 静态信息展示 */}
                    {position?.piece ? (
                      <div className="mt-2 rounded bg-gray-50 p-2 text-xs">
                        <div className="font-medium">{position.piece.name}</div>
                        {position.piece.alias && (
                          <div className="text-blue-600">
                            [{position.piece.alias}]
                          </div>
                        )}
                        {position.piece.describe && (
                          <div className="text-gray-500">
                            {position.piece.describe}
                          </div>
                        )}
                        <div className="text-gray-400">
                          分数: {position.piece.score}
                        </div>
                      </div>
                    ) : (
                      <div className="mt-2 text-xs text-gray-400">无数据</div>
                    )}
                  </div>
                )
              })}
            </div>
          </div>
        </Card>

        {/* 示例：不同使用方式对比 */}
        <Card className="p-4">
          <div className="space-y-4">
            <h3 className="text-lg font-semibold">三种使用方式对比</h3>
            <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
              {[
                {
                  title: '1. URL参数格式（推荐）',
                  code: [
                    `imageId="${currentGroup}"`,
                    `row={1} col={1}`,
                    `baseUrl="${baseUrl}"`
                  ],
                  component: (
                    <ImageSliceViewer
                      imageId={currentGroup}
                      row={1}
                      col={1}
                      baseUrl={baseUrl}
                      width={56}
                      height={56}
                      alt="URL参数格式"
                    />
                  )
                },
                {
                  title: '2. ImageSliceId格式',
                  code: [
                    `imageSliceId="${currentGroup}_1_1"`,
                    `baseUrl="${baseUrl}"`
                  ],
                  component: (
                    <ImageSliceViewer
                      imageSliceId={`${currentGroup}_1_1`}
                      baseUrl={baseUrl}
                      width={56}
                      height={56}
                      alt="ImageSliceId格式"
                    />
                  )
                },
                {
                  title: '3. 传统格式',
                  code: [
                    `imageUrl="${baseUrl}${currentGroup}"`,
                    `position={{ row: 1, col: 1 }}`
                  ],
                  component: (
                    <ImageSliceViewer
                      imageUrl={`${baseUrl}${currentGroup}`}
                      position={{ row: 1, col: 1 }}
                      width={56}
                      height={56}
                      alt="传统格式"
                    />
                  )
                }
              ].map((example, index) => {
                const position = allPositions.find(
                  (p) => p.row === 1 && p.col === 1
                )

                return (
                  <div key={index} className="rounded-lg border p-4">
                    <h4 className="mb-2 font-medium">{example.title}</h4>
                    <div className="mb-2 text-center">
                      <div className="group relative inline-block">
                        {example.component}

                        {/* Hover 卡片 */}
                        {position?.piece && (
                          <div className="pointer-events-none absolute bottom-full left-1/2 z-10 mb-2 -translate-x-1/2 opacity-0 transition-opacity duration-200 group-hover:opacity-100">
                            <div className="whitespace-nowrap rounded-lg border border-gray-200 bg-white p-3 text-xs shadow-lg">
                              <div className="mb-1 font-medium text-gray-800">
                                {position.piece.name}
                              </div>
                              {position.piece.alias && (
                                <div className="mb-1 font-mono text-blue-600">
                                  [{position.piece.alias}]
                                </div>
                              )}
                              {position.piece.describe && (
                                <div className="mb-1 max-w-48 whitespace-normal text-gray-600">
                                  {position.piece.describe}
                                </div>
                              )}
                              <div className="text-gray-500">
                                位置: ({position.row}, {position.col}) | 分数:{' '}
                                {position.piece.score}
                              </div>
                              <div className="absolute left-1/2 top-full -mt-1 -translate-x-1/2">
                                <div className="size-2 rotate-45 border-b border-r border-gray-200 bg-white"></div>
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>

                    <code className="block rounded bg-gray-100 p-2 text-xs">
                      {example.code.map((line, i) => (
                        <span key={i}>
                          {line}
                          {i < example.code.length - 1 && <br />}
                        </span>
                      ))}
                    </code>

                    {/* 静态信息展示 */}
                    {position?.piece ? (
                      <div className="mt-2 rounded bg-blue-50 p-2 text-xs">
                        <div className="font-medium">{position.piece.name}</div>
                        {position.piece.alias && (
                          <div className="text-blue-600">
                            [{position.piece.alias}]
                          </div>
                        )}
                        {position.piece.describe && (
                          <div className="text-gray-500">
                            {position.piece.describe}
                          </div>
                        )}
                        <div className="text-gray-400">
                          分数: {position.piece.score}
                        </div>
                      </div>
                    ) : (
                      <div className="mt-2 text-xs text-gray-400">无数据</div>
                    )}
                  </div>
                )
              })}
            </div>
          </div>
        </Card>

        {/* 使用说明 */}
        <Card className="p-4">
          <div className="space-y-2">
            <h3 className="text-lg font-semibold">使用说明</h3>
            <ul className="space-y-1 text-sm text-gray-600">
              <li>• 数据来源于 usePieceStore 中的碎片数据</li>
              <li>
                • 根据碎片的 avatar 格式（如
                &quot;14097_1_2&quot;）自动分组和定位
              </li>
              <li>
                • avatar 格式: imageId_row_col（如 14097_1_2
                表示图片14097的第1行第2列）
              </li>
              <li>• 每个图片被切分为5x5共25个小图片</li>
              <li>• 显示碎片的名称、别名(alias)和描述(describe)信息</li>
              <li>
                • <strong>鼠标悬停</strong>在图片上可查看详细的碎片信息卡片
              </li>
              <li>• 点击任意小图片可以查看控制台输出的详细信息</li>
              <li>• 图片会自动缓存，点击&quot;清理缓存&quot;可重新加载</li>
              <li>• 位置坐标从(0,0)到(4,4)，左上角为(0,0)</li>
            </ul>
            <div className="mt-4 rounded border border-yellow-200 bg-yellow-50 p-3">
              <h4 className="mb-2 font-medium text-yellow-800">
                ✨ 新功能特性:
              </h4>
              <div className="space-y-1 text-sm text-yellow-700">
                <div>
                  <strong>Hover 效果：</strong>{' '}
                  鼠标悬停在图片上会显示包含碎片详细信息的浮动卡片
                </div>
                <div>
                  <strong>智能数据传递：</strong>{' '}
                  组件自动关联位置和碎片数据，无需手动查找
                </div>
                <div>
                  <strong>别名显示：</strong>{' '}
                  在网格中和hover卡片中都会显示碎片的别名信息
                </div>
                <div>
                  <strong>描述信息：</strong>{' '}
                  完整的碎片描述会在hover时显示，支持多行文本
                </div>
              </div>
            </div>
            <div className="mt-4 rounded bg-blue-50 p-3">
              <h4 className="mb-2 font-medium">数据分组逻辑:</h4>
              <div className="space-y-1 text-sm">
                <div>
                  <strong>Avatar 解析：</strong> 从 &quot;imageId_row_col&quot;
                  格式中提取图片ID和位置信息
                </div>
                <div>
                  <strong>自动分组：</strong> 根据提取的图片ID自动分组
                </div>
                <div>
                  <strong>位置映射：</strong> 根据 row 和 col
                  信息精确定位碎片在网格中的位置
                </div>
                <div>
                  <strong>交互功能：</strong>{' '}
                  点击切片时会显示该位置对应碎片的详细信息
                </div>
              </div>
            </div>
            <div className="mt-4 rounded bg-green-50 p-3">
              <h4 className="mb-2 font-medium">三种使用方式:</h4>
              <div className="space-y-1 text-sm">
                <div>
                  <strong>1. URL参数格式（推荐）：</strong> 直接传递 imageId,
                  row, col 参数
                </div>
                <div>
                  <strong>2. ImageSliceId格式：</strong> 使用
                  &quot;imageId_row_col&quot; 格式的字符串
                </div>
                <div>
                  <strong>3. 传统格式：</strong> 使用 imageUrl 和 position 对象
                </div>
              </div>
            </div>
          </div>
        </Card>
      </div>
    </div>
  )
}
